<?php
gatekeeper();
$DEFAULT = "";
elgg_make_sticky_form ( 'assigntask' );
$title = get_input ( 'title', $DEFAULT );
$description = get_input ( 'description', $DEFAULT );
$deadline = get_input ( 'deadline', $DEFAULT );
$assignto = get_input ( 'assignto', - 1 );
$group_guid = get_input ( 'group_guid', $DEFAULT );
$assignment_guid = get_input('assignment_guid', $DEFAULT);

if ($title != $DEFAULT && $description != $DEFAULT && $deadline != $DEFAULT && $assignto != - 1) {

	
	if ($group_guid) {
		$project = get_entity ( $assignto );
		if (!$project) {
			// assign to all
			if($assignment_guid != $DEFAULT ){
				delete_entity($assignment_guid);
			}
			
			$class = explode ( "`", $assignto );
			$metadata_options = array (
					array (
							'name' => 'group_project',
							'value' => $class[0],
					),
					array (
							'name' => 'semester',
							'value' => $class[1]
					),
					array (
							'name' => 'academic_year',
							'value' => $class[2]
					)
			);
			
			$projects = elgg_get_entities ( array (
					'type' => "object",
					'subtype' => 'project',
					'container_guid' => $group_guid,
					'metadata_name_value_pairs' => $metadata_options
			) );
			foreach ( $projects as $project ) {
				$assignment = new ElggObject ();
				$assignment->subtype = "assignment";
				$assignment->title = $title;
				$assignment->description = $description;
				$assignment->deadline = $deadline;
				$assignment->owner_guid = elgg_get_logged_in_user_guid();
				$assignment->container_guid = $project->guid;
				$assignment->access_id = ACCESS_LOGGED_IN;
				$assignment->save();
				

			}
		} else {
			// assign to a specific project
			$project = get_entity ( $assignto );
			if($assignment_guid != $DEFAULT){
				$assignment = get_entity ($assignment_guid);
			} else {
				$assignment = new ElggObject ();
				$assignment->subtype = "assignment";
				$assignment->owner_guid = elgg_get_logged_in_user_guid();
				$assignment->access_id = ACCESS_LOGGED_IN;
			}
			
			if ($project) {
				$assignment->title = $title;
				$assignment->description = $description;
				$assignment->deadline = $deadline;
				$assignment->container_guid = $project->guid;
				$assignment->save();
// 				$project->addRelationship($assignment->guid, "assignto");
			}
		}
		elgg_clear_sticky_form ( 'assigntask' );
		$listproj_url = elgg_get_site_url () . "submana/listpro/$group_guid";
		forward ( $listproj_url );
	} else {
		register_error ( elgg_echo ( 'submana:message:failded' ) );
		forward ( REFERER );
	}
} else {
	register_error ( elgg_echo ( 'submana:project:assignrmissing' ) );
	//forward ( REFERER );
}